package com.cy.pj.goods.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultGoodsDao implements GoodsDao {
    @Autowired
    private DataSource dataSource;
    @Override
    public List<Map<String,Object>> findGoods(){
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        String sql = "select * from tb_goods";
        try {//1.获取连接对象
            conn = dataSource.getConnection();
            //2.创建Statement对象(负责发送sql-sql传送器)
            stmt = conn.createStatement();
            //3.发送sql
            rs = stmt.executeQuery(sql);
            //4.处理结果集
            List<Map<String,Object>> list = new ArrayList<>();
            while (rs.next()){//循环一次取一行,一行记录映射为一个map对象
                list.add(rowMap(rs));
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }finally {//5.关闭资源
            close(rs,stmt,conn);
        }

    }

    private Map<String, Object> rowMap(ResultSet rs) throws SQLException {
        Map<String,Object> rowMap = new HashMap<>();
        ResultSetMetaData rsmd = rs.getMetaData();//获取结果集中的元数据(描述数据的数据)
        int columnCount = rsmd.getColumnCount();
        for (int i=0;i<columnCount;i++){
            rowMap.put(rsmd.getColumnLabel(i+1), rs.getObject(rsmd.getColumnLabel(i+1)));
        }
        return rowMap;
    }
    private void close(ResultSet rs,Statement stmt,Connection conn){
        if(rs!=null)try{rs.close();}catch(Exception e){e.printStackTrace();}
        if(stmt!=null)try{stmt.close();}catch(Exception e){e.printStackTrace();}
        if(conn!=null)try{conn.close();}catch(Exception e){e.printStackTrace();}
    }
}
